package com.yanghui.lingyue.functions.timer

import com.icedata.sika.database.Column
import com.icedata.sika.database.Table
import com.yanghui.lingyue.bot.Bot
import com.yanghui.lingyue.functions.defaultFunction.SendMessage
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.util.*

object SendTimerMessage {

    private const val name = "TimerMessage"
    private val messageList: LinkedList<TimerMessage> = LinkedList()

    fun init() {
        messageList.clear()
        Bot.sikaCore.databaseCopy<TimerMessageRecord>().forEach {
            messageList.add(TimerMessage(it))
        }
        if (!TimeScheduler.taskMap.keys.contains(name)) {
            TimeScheduler.taskMap[name] = { time->
                messageList.forEach {
                    it.sendMessage(time)
                }
            }
        }
    }
}

@Table("TimerMessage", "", "timerMessageID")
data class TimerMessageRecord(

    @Column("timerMessageID")
    var id: Int,

    @Column("timerMessage")
    var message: String,

    @Column("sendTime")
    var sendTime: String,

    @Column("enableGroup")
    var enableGroup: String,

    @Column("disabledGroup")
    var disabledGroup: String,

    @Column("antiChoose")
    var antiChoose: Boolean
) {
    constructor() : this(-1, "", "", "", "", true)
}

class TimerMessage(messageRecord: TimerMessageRecord) {
    private val enableGroupList: LinkedList<Long> = LinkedList()
    private val message: String by lazy {
        messageRecord.message
    }
    private val sendTime: String by lazy {
        messageRecord.sendTime
    }

    init {
        if (!messageRecord.antiChoose) {
            messageRecord.enableGroup.split(",").forEach {
                enableGroupList.add(it.toLong())
            }
        } else {
            val disableGroupList = messageRecord.disabledGroup.split(",")
            Bot.groupList.forEach { (id, _) ->
                if (id.toString() !in disableGroupList) {
                    enableGroupList.add(id)
                }
            }
        }
    }

    fun sendMessage(time: String) {
        if (time == sendTime)
            GlobalScope.launch(Dispatchers.IO) {
                enableGroupList.forEach {
                    SendMessage.sendMessage(message, it)
                }
            }
    }
}